package com.sline.servlet.demo1_servlet._01_base;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class _04_Calculator extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        String firstStr = req.getParameter("first");
        String secondStr = req.getParameter("second");
        String operator = req.getParameter("operator");
        System.out.println("first:" + firstStr + " - second:" + secondStr + " - operator:" + operator);
        int result = 0;
        if ((firstStr != null && !"".equals(firstStr.trim())) && (secondStr != null && !"".equals(secondStr.trim()))) {
            int firstNum = Integer.valueOf(firstStr);
            int secondNum = Integer.valueOf(secondStr);
            if ("+".equals(operator)) {
                result = firstNum + secondNum;
            } else if ("-".equals(operator)) {
                result = firstNum - secondNum;
            } else if ("*".equals(operator)) {
                result = firstNum * secondNum;
            } else if ("/".equals(operator)) {
                result = firstNum / secondNum;
            }
        }

        PrintWriter writer = resp.getWriter();
        writer.println("<form action='/servlet/calculator'>");
        writer.println("<input name='first' value='"+ (firstStr != null ? firstStr : "") +"'/>");
        writer.println("<select name='operator'>");
        writer.println("<option>+</option>");
        writer.println("<option>-</option>");
        writer.println("<option>*</option>");
        writer.println("<option>/</option>");
        writer.println("</select>");
        writer.println("<input name='second' value='" + (secondStr != null ? secondStr : "") + "'/>");
        writer.println("<input type='submit' value='='>");
        writer.println("<input value='" + result + "' disabled='disabled'>");
        writer.println("</form>");
    }
}
